<script lang="ts" setup>
import { createVNode, onBeforeUnmount, onMounted, ref, render, VNode } from 'vue'
import * as echarts from 'echarts'
import { queryMap } from '@/api/map'
import { getMapJsonResponseData, propertiesEntity } from '@/api/map/types/map'
import { ElLoading, ElMessage } from 'element-plus'
import boudaryJSON from '@/assets/map/cleaned_china.json'
import mapJSON from '@/assets/map/100000_full.json'
import AbnormalBattery from '@/assets/images/ic-abnormal-battery.png'
import AlarmBattery from '@/assets/images/ic-alarm-battery.png'
import NormalBattery from '@/assets/images/ic-normal-battery.png'
import BorderBox4BatteryInfo from '@/components/basic/BorderBox4BatteryInfo.vue'
import BorderBox4BatterySwapInfo from '@/components/basic/BorderBox4BatterySwapInfo.vue'
import BorderBox4ChargeBatteryInfo from '@/components/basic/BorderBox4ChargeBatteryInfo.vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/modules/user'
import { LoadingInstance } from 'element-plus/es/components/loading/src/loading.mjs'
import { basicMapData } from '@/types'
import BatterySwapImg from '@/assets/images/batteryswap.png'
import ChargeBatteryImg from '@/assets/images/ic_charge_battery.png'
import { getToken } from '@/utils/cache/cookies'
import { gcj02towgs84 } from 'coordtransform'
import { booleanPointInPolygon } from '@turf/turf'
const router = useRouter()
const charts = ref<echarts.ECharts | null>(null)
const {
  getMapAdcode,
  getMapAreaName,
  getMapLevel,
  setMapAdcode,
  setMapAreaName,
  setMapLevel,
  getMapTree,
  pushMapTree,
  popMapTree,
} = useUserStore()
/** 点击地图时push，点返回时pop */
// const deepTree = ref<any[]>(getMapTree() ?? [])
/** 当前地名 */
// const areaName = ref<string>(getMapAreaName() ?? '')
/** 当前行政区划 */
// const areaCode = ref<string>(getMapAdcode() ?? '100000')
/** 当前行政等级 */
// const areaLevel = ref<string>(getMapLevel() ?? 'country')
/** 当前所属地名（详细） */
const totalAreaName = ref<string[]>([])
const emits = defineEmits(['clear-interval', 'open-interval'])
type MapType = '电池总数' | '换电柜总数' | '充电柜总数'
const type = ref<MapType>('电池总数')
/** 数据 */
const MapData = ref<basicMapData[]>([])
/** loading */
const loadingService = ref<LoadingInstance>()
// 2. 复用的 Vue 组件实例
const batteryVnode = ref<VNode | null>(null)
const batteryAppMounted = ref<boolean>(false)
// 2. 复用的 Vue 组件实例
const batterySwapVnode = ref<VNode | null>(null)
const batterySwapAppMounted = ref<boolean>(false)
// 2. 复用的 Vue 组件实例
const chargeBatteryVnode = ref<VNode | null>(null)
const chargeBatteryAppMounted = ref<boolean>(false)
const createTooltipVNode = (type: string) => {
  const tooltipContainer = document.createElement('div')
  tooltipContainer.id = 'tooltip-' + type + '-container'
  tooltipContainer.style.position = 'absolute'
  tooltipContainer.style.pointerEvents = 'none' // 让容器不影响鼠标事件
  tooltipContainer.style.zIndex = '1000'
  document.body.appendChild(tooltipContainer)
  return tooltipContainer
}
const tooltipBatteryContainer = createTooltipVNode('battery')
const tooltipBatterySwapContainer = createTooltipVNode('battery-swap')
const tooltipChargeBatteryContainer = createTooltipVNode('charge-battery')

/** 实例化地图 */
const initMapCharts = () => {
  if (charts.value != null && charts.value != undefined) {
    charts.value.dispose() //销毁
  }
  const MapContainer = document.getElementById('map-container')
  charts.value = echarts.init(MapContainer)
  handleMapClick()
}
/** 获取地图数据 */
const getData = async (adcode: string, level: string, isFull: boolean) => {
  const produceId =
    'https://www.isqqw.com/asset/get/areas_v3/' +
    level +
    '/' +
    adcode +
    (isFull ? '_full' : '') +
    '.json'
  try {
    const res = await queryMap({
      token: getToken() ?? '',
      channel: 'Service',
      produceId,
    })
    charts.value?.hideLoading()
    return res.resultData
  } catch (error) {
    console.error(error)
    charts.value?.hideLoading()
    return
  }
}
/** 获取地图配置 */
interface mapDataEntity {
  value: propertiesEntity
  name: string
  label: { show: boolean }
}
const getBatteryOptions = (
  areaName: string,
  mapData: mapDataEntity[] | undefined,
  batteryData: basicMapData[],
) => {
  if (!mapData) return
  const normalBatteryData = formatScatterData(
    batteryData.filter((item) => item.abnormalStatus === '0'),
    '电池',
  )
  const AbnormalBatteryData = formatScatterData(
    batteryData.filter((item) => item.abnormalStatus === '1'),
    '电池',
  )
  const AlarmBatteryData = formatScatterData(
    batteryData.filter((item) => item.abnormalStatus === '2'),
    '电池',
  )
  const option = {
    geo: [
      {
        layoutCenter: ['50%', '50%'], //位置
        layoutSize: '100%', //大小
        show: true,
        map: areaName + 'boudary',
        roam: false,
        zoom: 1,
        zlevel: 0,
        aspectScale: 1,
        label: {
          show: false,
          color: '#fff',
        },
        emphasis: {
          label: {
            show: true,
            color: '#fff',
          },
          itemStyle: {
            areaColor: '#45AAFF',
            // borderWidth: 0
          },
        },
        itemStyle: {
          areaColor: {
            type: 'radial',
            x: 0.6,
            y: 0.6,
            r: 1,
            colorStops: [
              {
                offset: 0.1,
                color: '#000', // 0% 处的颜色
              },
              {
                offset: 1,
                color: 'rgba(22, 123, 229, 1)', // 100% 处的颜色
              },
            ],
            global: false, // 缺省为 false
          },
          borderColor: 'rgba(22, 135, 255, 1)',
          borderWidth: 1,
          shadowColor: '#073E80',
          shadowOffsetY: 10,
        },
      },
      {
        layoutCenter: ['50%', '50%'], //位置
        layoutSize: '100%', //大小
        show: true,
        map: areaName,
        zlevel: 1,
        roam: false,
        zoom: 1,
        aspectScale: 1,
        silent: false,
        label: {
          show: false,
          color: '#fff',
        },
        emphasis: {
          label: {
            show: true,
            color: '#fff',
            fontSize: 30,
          },
          itemStyle: {
            areaColor: '#45AAFF',
          },
        },
        itemStyle: {
          areaColor: 'transparent',
          borderColor: 'rgba(22, 135, 255, 1)',
          borderWidth: 1,
        },
        select: {
          label: {
            show: true,
            color: '#fff',
            fontSize: 30,
          },
          itemStyle: {
            areaColor: '#45AAFF',
          },
        },
      },
      {
        type: 'map',
        map: areaName,
        zlevel: -1,
        aspectScale: 1,
        zoom: 1,
        layoutCenter: ['50%', '51%'],
        layoutSize: '100%',
        roam: false,
        silent: true,
        itemStyle: {
          borderWidth: 1,
          borderColor: '#FFF',
          shadowColor: '#1465B7',
          shadowOffsetY: 10,
          // shadowBlur: 15,
          areaColor: '#1465B7',
        },
      },
      {
        type: 'map',
        map: areaName,
        zlevel: -2,
        aspectScale: 1,
        zoom: 1,
        layoutCenter: ['50%', '52%'],
        layoutSize: '100%',
        roam: false,
        silent: true,
        itemStyle: {
          borderWidth: 0,
          // borderColor: "rgba(57, 132, 188,0.4)",
          borderColor: 'transpercent',
          shadowColor: '#2379BF',
          shadowOffsetY: 10,
          shadowBlur: 15,
          areaColor: '#2379BF',
        },
      },
    ],
    series: [
      {
        type: 'map',
        map: areaName,
        geoIndex: 1,
        aspectScale: 1, //长宽比
        zoom: 1,
        showLegendSymbol: true,
        roam: true,
        layoutCenter: ['50%', '50%'],
        layoutSize: '100%',
        animation: true,
        markPoint: {
          symbol: 'none',
        },
        data: mapData,
      },
      {
        type: 'scatter',
        coordinateSystem: 'geo',
        geoIndex: 1,
        zlevel: 2,
        large: true,
        symbol: 'image://' + NormalBattery,
        z: 999,
        symbolSize: [20, 20],
        data: normalBatteryData,
        name: '正常电池',
      },
      {
        type: 'scatter',
        coordinateSystem: 'geo',
        geoIndex: 1,
        zlevel: 2,
        large: true,
        symbol: 'image://' + AbnormalBattery,
        z: 999,
        symbolSize: [20, 20],
        data: AbnormalBatteryData,
        name: '异常电池',
      },
      {
        type: 'scatter',
        coordinateSystem: 'geo',
        geoIndex: 1,
        zlevel: 2,
        large: true,
        symbol: 'image://' + AlarmBattery,
        z: 999,
        symbolSize: [20, 20],
        data: AlarmBatteryData,
        name: '告警电池',
      },
    ],
    tooltip: {
      trigger: 'item',
      confine: true,
      formatter: () => {
        return ''
      },
      enterable: true,
      extraCssText: 'display:none;',
    },
    legend: {
      show: true,
      itemGap: 30,
      orient: 'vertical',
      left: 0,
      bottom: 0,
      textStyle: {
        color: '#FFF',
        fontSize: 28,
      },
      itemWidth: 40,
      itemHeight: 40,
      backgroundColor: 'rgba(6,17,40,0.5)',
      borderWidth: 2,
      borderColor: '#212D4C',
      padding: 50,
    },
  }
  return option
}
const getBoxOptions = (
  areaName: string,
  mapData: mapDataEntity[] | undefined,
  data: basicMapData[],
) => {
  if (!mapData) return
  const batterySwapScatterData = formatScatterData(data, '换电柜')
  const option = {
    geo: [
      {
        layoutCenter: ['50%', '50%'], //位置
        layoutSize: '100%', //大小
        show: true,
        map: areaName + 'boudary',
        roam: false,
        zoom: 1,
        zlevel: 0,
        aspectScale: 1,
        label: {
          show: false,
          color: '#fff',
        },
        emphasis: {
          label: {
            show: true,
            color: '#fff',
          },
          itemStyle: {
            areaColor: '#45AAFF',
            // borderWidth: 0
          },
        },
        itemStyle: {
          areaColor: {
            type: 'radial',
            x: 0.6,
            y: 0.6,
            r: 1,
            colorStops: [
              {
                offset: 0.1,
                color: '#000', // 0% 处的颜色
              },
              {
                offset: 1,
                color: 'rgba(22, 123, 229, 1)', // 100% 处的颜色
              },
            ],
            global: false, // 缺省为 false
          },
          borderColor: 'rgba(22, 135, 255, 1)',
          borderWidth: 1,
          shadowColor: '#073E80',
          shadowOffsetY: 10,
        },
      },
      {
        layoutCenter: ['50%', '50%'], //位置
        layoutSize: '100%', //大小
        show: true,
        map: areaName,
        zlevel: 1,
        roam: false,
        zoom: 1,
        aspectScale: 1,
        silent: false,
        label: {
          show: false,
          color: '#fff',
        },
        emphasis: {
          label: {
            show: true,
            color: '#fff',
            fontSize: 30,
          },
          itemStyle: {
            areaColor: '#45AAFF',
          },
        },
        itemStyle: {
          areaColor: 'transparent',
          borderColor: 'rgba(22, 135, 255, 1)',
          borderWidth: 1,
        },
        select: {
          label: {
            show: true,
            color: '#fff',
            fontSize: 30,
          },
          itemStyle: {
            areaColor: '#45AAFF',
          },
        },
      },
      {
        type: 'map',
        map: areaName,
        zlevel: -1,
        aspectScale: 1,
        zoom: 1,
        layoutCenter: ['50%', '51%'],
        layoutSize: '100%',
        roam: false,
        silent: true,
        itemStyle: {
          borderWidth: 1,
          borderColor: '#FFF',
          shadowColor: '#1465B7',
          shadowOffsetY: 10,
          // shadowBlur: 15,
          areaColor: '#1465B7',
        },
      },
      {
        type: 'map',
        map: areaName,
        zlevel: -2,
        aspectScale: 1,
        zoom: 1,
        layoutCenter: ['50%', '52%'],
        layoutSize: '100%',
        roam: false,
        silent: true,
        itemStyle: {
          borderWidth: 0,
          // borderColor: "rgba(57, 132, 188,0.4)",
          borderColor: 'transpercent',
          shadowColor: '#2379BF',
          shadowOffsetY: 10,
          shadowBlur: 15,
          areaColor: '#2379BF',
        },
      },
    ],
    series: [
      {
        type: 'map',
        map: areaName,
        geoIndex: 1,
        aspectScale: 1, //长宽比
        zoom: 1,
        showLegendSymbol: true,
        roam: true,
        layoutCenter: ['50%', '50%'],
        layoutSize: '100%',
        animation: true,
        markPoint: {
          symbol: 'none',
        },
        data: mapData,
      },
      {
        type: 'scatter',
        coordinateSystem: 'geo',
        geoIndex: 1,
        zlevel: 2,
        large: true,
        symbol: 'image://' + BatterySwapImg,
        z: 999,
        symbolSize: [20, 20],
        data: batterySwapScatterData,
        name: '换电柜',
      },
    ],
    tooltip: {
      trigger: 'item',
      confine: true,
      formatter: () => {
        return ''
      },
      enterable: true,
      extraCssText: 'display:none;',
    },
    legend: {
      show: true,
      itemGap: 30,
      orient: 'vertical',
      left: 0,
      bottom: 0,
      textStyle: {
        color: '#FFF',
        fontSize: 28,
      },
      itemWidth: 40,
      itemHeight: 40,
      backgroundColor: 'rgba(6,17,40,0.5)',
      borderWidth: 2,
      borderColor: '#212D4C',
      padding: 50,
    },
  }
  return option
}
const getChargeBatteryOptions = (
  areaName: string,
  mapData: mapDataEntity[] | undefined,
  data: basicMapData[],
) => {
  if (!mapData) return
  const chargeBatteryScatterData = formatScatterData(data, '充电柜')
  const option = {
    geo: [
      {
        layoutCenter: ['50%', '50%'], //位置
        layoutSize: '100%', //大小
        show: true,
        map: areaName + 'boudary',
        roam: false,
        zoom: 1,
        zlevel: 0,
        aspectScale: 1,
        label: {
          show: false,
          color: '#fff',
        },
        emphasis: {
          label: {
            show: true,
            color: '#fff',
          },
          itemStyle: {
            areaColor: '#45AAFF',
            // borderWidth: 0
          },
        },
        itemStyle: {
          areaColor: {
            type: 'radial',
            x: 0.6,
            y: 0.6,
            r: 1,
            colorStops: [
              {
                offset: 0.1,
                color: '#000', // 0% 处的颜色
              },
              {
                offset: 1,
                color: 'rgba(22, 123, 229, 1)', // 100% 处的颜色
              },
            ],
            global: false, // 缺省为 false
          },
          borderColor: 'rgba(22, 135, 255, 1)',
          borderWidth: 1,
          shadowColor: '#073E80',
          shadowOffsetY: 10,
        },
      },
      {
        layoutCenter: ['50%', '50%'], //位置
        layoutSize: '100%', //大小
        show: true,
        map: areaName,
        zlevel: 1,
        roam: false,
        zoom: 1,
        aspectScale: 1,
        silent: false,
        label: {
          show: false,
          color: '#fff',
        },
        emphasis: {
          label: {
            show: true,
            color: '#fff',
            fontSize: 30,
          },
          itemStyle: {
            areaColor: '#45AAFF',
          },
        },
        itemStyle: {
          areaColor: 'transparent',
          borderColor: 'rgba(22, 135, 255, 1)',
          borderWidth: 1,
        },
        select: {
          label: {
            show: true,
            color: '#fff',
            fontSize: 30,
          },
          itemStyle: {
            areaColor: '#45AAFF',
          },
        },
      },
      {
        type: 'map',
        map: areaName,
        zlevel: -1,
        aspectScale: 1,
        zoom: 1,
        layoutCenter: ['50%', '51%'],
        layoutSize: '100%',
        roam: false,
        silent: true,
        itemStyle: {
          borderWidth: 1,
          borderColor: '#FFF',
          shadowColor: '#1465B7',
          shadowOffsetY: 10,
          // shadowBlur: 15,
          areaColor: '#1465B7',
        },
      },
      {
        type: 'map',
        map: areaName,
        zlevel: -2,
        aspectScale: 1,
        zoom: 1,
        layoutCenter: ['50%', '52%'],
        layoutSize: '100%',
        roam: false,
        silent: true,
        itemStyle: {
          borderWidth: 0,
          // borderColor: "rgba(57, 132, 188,0.4)",
          borderColor: 'transpercent',
          shadowColor: '#2379BF',
          shadowOffsetY: 10,
          shadowBlur: 15,
          areaColor: '#2379BF',
        },
      },
    ],
    series: [
      {
        type: 'map',
        map: areaName,
        geoIndex: 1,
        aspectScale: 1, //长宽比
        zoom: 1,
        showLegendSymbol: true,
        roam: true,
        layoutCenter: ['50%', '50%'],
        layoutSize: '100%',
        animation: true,
        markPoint: {
          symbol: 'none',
        },
        data: mapData,
      },
      {
        type: 'scatter',
        coordinateSystem: 'geo',
        geoIndex: 1,
        zlevel: 2,
        large: true,
        symbol: 'image://' + ChargeBatteryImg,
        z: 999,
        symbolSize: [20, 20],
        data: chargeBatteryScatterData,
        name: '充电柜',
      },
    ],
    tooltip: {
      trigger: 'item',
      confine: true,
      formatter: () => {
        return ''
      },
      enterable: true,
      extraCssText: 'display:none;',
    },
    legend: {
      show: true,
      itemGap: 30,
      orient: 'vertical',
      left: 0,
      bottom: 0,
      textStyle: {
        color: '#FFF',
        fontSize: 28,
      },
      itemWidth: 40,
      itemHeight: 40,
      backgroundColor: 'rgba(6,17,40,0.5)',
      borderWidth: 2,
      borderColor: '#212D4C',
      padding: 50,
    },
  }
  return option
}
const ChangeMapOptions = (
  areaName: string,
  mapData: mapDataEntity[] | undefined,
  data?: basicMapData[],
) => {
  if (!data) return
  switch (type.value) {
    case '电池总数':
      return getBatteryOptions(areaName, mapData, data)
    case '换电柜总数':
      return getBoxOptions(areaName, mapData, data)
    case '充电柜总数':
      return getChargeBatteryOptions(areaName, mapData, data)
  }
}
const getJSON = async () => {
  const areaCode = getMapAdcode()
  const areaLevel = getMapLevel()
  const areaName = getMapAreaName()
  if (areaCode === '100000') {
    return {
      boudaryData: JSON.parse(JSON.stringify(boudaryJSON)),
      data: JSON.parse(JSON.stringify(mapJSON)),
    }
  } else {
    console.log(areaCode, areaLevel, areaName)

    return {
      boudaryData: await getData(areaCode, areaLevel, false),
      data: await getData(areaCode, areaLevel, true),
    }
  }
}
/** 首次挂载地图时 */
const FirstLoad = async (d: basicMapData[], t: MapType) => {
  const areaCode = getMapAdcode()
  const areaName = getMapAreaName()
  charts.value?.clear()
  type.value = t
  const res = await getJSON()
  echarts.registerMap(areaName + 'boudary', res.boudaryData)
  echarts.registerMap(areaName, res.data)
  MapData.value = d
  const option = ChangeMapOptions(
    areaName,
    formatMapParams(res.data),
    filterScatterData(res.boudaryData),
  )
  if (option) {
    pushMapTree({ areaCode, areaName, option }, areaName)
    totalAreaName.value.push(areaName)
    charts.value?.setOption(option)
  }
}
/** 下钻地图流程 */
const deepProcess = async () => {
  loadingService.value = ElLoading.service({
    target: '.app-container',
    text: '加载中',
    fullscreen: false,
    customClass: 'full-screen-loading',
    svgViewBox: ' 0 0 65 65',
  })
  const areaCode = getMapAdcode()
  const areaLevel = getMapLevel()
  const areaName = getMapAreaName()
  const boudaryData = await getData(areaCode, areaLevel, false)
  const data = await getData(areaCode, areaLevel, true)
  echarts.registerMap(areaName + 'boudary', boudaryData as any)
  echarts.registerMap(areaName, data as any)

  const option = ChangeMapOptions(areaName, formatMapParams(data), filterScatterData(boudaryData))
  if (option) {
    pushMapTree({ areaCode, areaName, option }, areaName)
    totalAreaName.value.push(areaName)
    charts.value?.setOption(option)
  }
  loadingService.value?.close()
  emits('clear-interval')
}
/** 处理地图事件 */
const handleMapClick = () => {
  charts.value?.on('click', 'series.map', (params: any) => {
    echartsMapClick(params)
  })
  charts.value?.on('mouseover', 'series.scatter', (params: any) => {
    const data = params.data[2]
    if (!data) return
    if (data.type === '电池') {
      if (!batteryAppMounted.value) {
        batteryVnode.value = createVNode(BorderBox4BatteryInfo, { data: data })
        render(batteryVnode.value, tooltipBatteryContainer)
        batteryAppMounted.value = true
      } else {
        // 组件已经挂载，更新 props 数据
        batteryVnode.value!.component!.props.data = data
      }
      // 根据鼠标位置更新容器位置
      const [x, y] = [params.event.event.pageX, params.event.event.pageY]
      tooltipBatteryContainer.style.left = `${x + 10}px`
      tooltipBatteryContainer.style.top = `${y + 10}px`
    } else if (data.type === '换电柜') {
      if (!batterySwapAppMounted.value) {
        batterySwapVnode.value = createVNode(BorderBox4BatterySwapInfo, { data: data })
        render(batterySwapVnode.value, tooltipBatterySwapContainer)
        batterySwapAppMounted.value = true
      } else {
        batterySwapVnode.value!.component!.props.data = data
      }
      // 根据鼠标位置更新容器位置
      const [x, y] = [params.event.event.pageX, params.event.event.pageY]
      tooltipBatterySwapContainer.style.left = `${x + 10}px`
      tooltipBatterySwapContainer.style.top = `${y + 10}px`
    } else {
      if (!chargeBatteryAppMounted.value) {
        chargeBatteryVnode.value = createVNode(BorderBox4ChargeBatteryInfo, { data: data })
        render(chargeBatteryVnode.value, tooltipChargeBatteryContainer)
        chargeBatteryAppMounted.value = true
      } else {
        chargeBatteryVnode.value!.component!.props.data = data
      }
      // 根据鼠标位置更新容器位置
      const [x, y] = [params.event.event.pageX, params.event.event.pageY]
      tooltipChargeBatteryContainer.style.left = `${x + 10}px`
      tooltipChargeBatteryContainer.style.top = `${y + 10}px`
    }
  })
  charts.value?.on('click', 'series.scatter', (params: any) => {
    const data = params.data[2]
    if (!data) return
    if (data.type === '电池') {
      router.push({
        name: 'BatteryInfo',
        query: {
          produceId: data.batteryLockId,
          type: '1',
        },
      })
    } else if (data.type === '换电柜') {
      router.push({
        name: 'BatterySwappingCabinetInfo',
        query: {
          produceId: data.boxId,
        },
      })
    } else {
      router.push({
        name: 'ChargeCabinetInfo',
        query: {
          produceId: data.boxId,
        },
      })
    }
    tooltipBatteryContainer.style.left = '-9999px'
    tooltipBatteryContainer.style.top = '-9999px'
    tooltipBatterySwapContainer.style.left = '-9999px'
    tooltipBatterySwapContainer.style.top = '-9999px'
    tooltipChargeBatteryContainer.style.left = '-9999px'
    tooltipChargeBatteryContainer.style.top = '-9999px'
  })
  // 6. 监听 tooltip 隐藏事件，隐藏容器
  charts.value?.on('mouseout', 'series.scatter', (params: any) => {
    const data = params.data[2]
    if (!data) return
    if (data.type === '电池') {
      tooltipBatteryContainer.style.left = '-9999px'
      tooltipBatteryContainer.style.top = '-9999px'
    } else if (data.type === '换电柜') {
      tooltipBatterySwapContainer.style.left = '-9999px'
      tooltipBatterySwapContainer.style.top = '-9999px'
    } else {
      tooltipChargeBatteryContainer.style.left = '-9999px'
      tooltipChargeBatteryContainer.style.top = '-9999px'
    }
  })
  charts.value?.on('legendselectchanged', (params: any) => {
    const curLegend = params.name
    const allLegend = Object.keys(params.selected)
    const selectedArr = Object.keys(params.selected).filter((el) => params.selected[el])
    const onlyCur = selectedArr.length + 1 === allLegend.length && !selectedArr.includes(curLegend)
    if (onlyCur) {
      allLegend.forEach((key) => {
        charts.value?.dispatchAction({
          type: key === curLegend ? 'legendSelect' : 'legendUnSelect',
          name: key,
        })
      })
    }
  })
}
/** 点击电池总数后续 */
const batteryTotalClick = () => {
  const batteryKey = ['正常电池', '异常电池', '告警电池']
  batteryKey.forEach((key) => {
    charts.value?.dispatchAction({
      type: 'legendSelect',
      name: key,
    })
  })
  charts.value?.dispatchAction({
    type: 'legendUnSelect',
    name: '电池站点',
  })
}
/** 地图点击事件 */
const echartsMapClick = (param: any) => {
  if (param.data.value.level == 'district') {
    ElMessage('该地区已经无法下钻')
    return
  }
  if (param.data.value.adcode === '100000_JD') return
  setMapAreaName(param.name)
  setMapAdcode(param.data.value.adcode)
  setMapLevel(param.data.value.level)
  deepProcess()
}

/** 辅助函数 */

const formatScatterData = (data: basicMapData[], t: string) => {
  const scatterData = data.map((item) => {
    return [
      item.longitude,
      item.latitude,
      {
        ...item,
        type: t,
      },
    ]
  })
  return scatterData
}
const filterScatterData = (b?: getMapJsonResponseData) => {
  if (!b) return
  return MapData.value.filter((item) => {
    const wgs84 = gcj02towgs84(+item.longitude, +item.latitude)
    return booleanPointInPolygon(wgs84, b.features[0].geometry)
  })
}
/** 格式化地图params数据 */
const formatMapParams = (data: getMapJsonResponseData | undefined) => {
  if (!data) {
    ElMessage.error('获取地图数据失败')
    return
  }
  return data.features.map((item) => {
    return {
      value: item.properties,
      name: item.properties.name,
      label: { show: false },
      opacity: 0,
    }
  })
}
/** 返回上一层地图 */
const handleBackNode = () => {
  const tree = getMapTree()
  if (tree.length <= 1) {
    return
  }
  popMapTree()
  totalAreaName.value.pop()
  const treeNode = tree[tree.length - 1]
  setMapAreaName(treeNode.areaName)
  setMapAdcode(treeNode.areaCode)
  setMapLevel(treeNode.areaLevel)
  charts.value?.clear()
  charts.value?.setOption(treeNode.option)
  if (tree[tree.length - 1].areaName === '中国') {
    emits('open-interval')
  }
}
defineExpose({
  handleBackNode,
  FirstLoad,
  batteryTotalClick,
})

onMounted(() => {
  initMapCharts()
})
onBeforeUnmount(() => {
  charts.value?.clear()
})
</script>

<template>
  <div class="map-container">
    <div class="map">
      <div id="map-container" />
    </div>
  </div>
</template>

<style scoped lang="scss">
.map-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  padding: 30px;
  color: #fff;
}
.map {
  width: 100%;
  height: 100%;
  flex: 1;
  #map-container {
    width: 100%;
    height: 100%;
    background-image: url(/src/assets/images/circle.png);
    background-repeat: no-repeat;
    background-position: center;
    background-size: 100%;
  }
}
:deep(.map-data-info-popover) {
  position: absolute;
  transition: all 0.5s;
}
:deep(.popover-button) {
  background: linear-gradient(180deg, #01e5fe 0%, #45aaff 100%);
  padding: 10px 20px;
}
</style>
